package draft

import (
	"fmt"
	"time"

	"github.com/google/uuid"
	"github.com/user/go-capcut/internal/util"
)

// Draft 表示一个CapCut草稿
type Draft struct {
	ID          string    `json:"id"`
	CreatedAt   time.Time `json:"created_at"`
	Width       int       `json:"width"`
	Height      int       `json:"height"`
	VideoTracks []Track   `json:"video_tracks"`
	AudioTracks []Track   `json:"audio_tracks"`
	TextTracks  []Track   `json:"text_tracks"`
	ImageTracks []Track   `json:"image_tracks"`
	Name        interface{}
	Duration    interface{}
	Tracks      []Track `json:"tracks"`
}

// Track 表示一个轨道
type Track struct {
	ID       string    `json:"id"`
	Name     string    `json:"name"`
	Type     string    `json:"type"`
	Segments []Segment `json:"segments"`
	Index    float64   `json:"index"`
}

// Segment 表示轨道中的一个片段
type Segment struct {
	ID          string                 `json:"id"`
	MaterialID  string                 `json:"material_id"`
	Start       float64                `json:"start"`
	End         float64                `json:"end"`
	TargetStart float64                `json:"target_start"`
	Speed       float64                `json:"speed"`
	Volume      float64                `json:"volume"`
	TransformX  float64                `json:"transform_x"`
	TransformY  float64                `json:"transform_y"`
	ScaleX      float64                `json:"scale_x"`
	ScaleY      float64                `json:"scale_y"`
	Rotation    float64                `json:"rotation"`
	Text        string                 `json:"text,omitempty"`
	FontName    string                 `json:"font_name,omitempty"`
	FontSize    float64                `json:"font_size,omitempty"`
	FontColor   string                 `json:"font_color,omitempty"`
	Effects     []Effect               `json:"effects,omitempty"`
	Keyframes   []Keyframe             `json:"keyframes,omitempty"`
	ExtraParams map[string]interface{} `json:"extra_params,omitempty"`
}

// Effect 表示一个特效
type Effect struct {
	ID        string                 `json:"id"`
	Type      string                 `json:"type"`
	Params    map[string]interface{} `json:"params"`
	Keyframes []Keyframe             `json:"keyframes"`
}

// Keyframe 表示一个关键帧
type Keyframe struct {
	Time       float64                `json:"time"`
	Property   string                 `json:"property"`
	Value      interface{}            `json:"value"`
	Parameters map[string]interface{} `json:"parameters,omitempty"`
}

// NewDraft 创建一个新的草稿
func NewDraft(width, height int) *Draft {
	return &Draft{
		ID:          generateDraftID(),
		CreatedAt:   time.Now(),
		Width:       width,
		Height:      height,
		VideoTracks: []Track{},
		AudioTracks: []Track{},
		TextTracks:  []Track{},
		ImageTracks: []Track{},
	}
}

// AddVideoTrack 添加视频轨道
func (d *Draft) AddVideoTrack(name string) *Track {
	track := Track{
		ID:       uuid.New().String(),
		Name:     name,
		Type:     "video",
		Segments: []Segment{},
	}
	d.VideoTracks = append(d.VideoTracks, track)
	return &d.VideoTracks[len(d.VideoTracks)-1]
}

// AddAudioTrack 添加音频轨道
func (d *Draft) AddAudioTrack(name string) *Track {
	track := Track{
		ID:       uuid.New().String(),
		Name:     name,
		Type:     "audio",
		Segments: []Segment{},
	}
	d.AudioTracks = append(d.AudioTracks, track)
	return &d.AudioTracks[len(d.AudioTracks)-1]
}

// AddTextTrack 添加文本轨道
func (d *Draft) AddTextTrack(name string) *Track {
	track := Track{
		ID:       uuid.New().String(),
		Name:     name,
		Type:     "text",
		Segments: []Segment{},
	}
	d.TextTracks = append(d.TextTracks, track)
	return &d.TextTracks[len(d.TextTracks)-1]
}

// AddImageTrack 添加图片轨道
func (d *Draft) AddImageTrack(name string) *Track {
	track := Track{
		ID:       uuid.New().String(),
		Name:     name,
		Type:     "image",
		Segments: []Segment{},
	}
	d.ImageTracks = append(d.ImageTracks, track)
	return &d.ImageTracks[len(d.ImageTracks)-1]
}

// AddVideoSegment 添加视频片段到轨道
func (t *Track) AddVideoSegment(materialID string, start, end, targetStart float64, options map[string]interface{}) *Segment {
	segment := Segment{
		ID:          uuid.New().String(),
		MaterialID:  materialID,
		Start:       start,
		End:         end,
		TargetStart: targetStart,
		Speed:       1.0,
		Volume:      1.0,
		TransformX:  0.0,
		TransformY:  0.0,
		ScaleX:      1.0,
		ScaleY:      1.0,
		Rotation:    0.0,
		Effects:     []Effect{},
		Keyframes:   []Keyframe{},
		ExtraParams: make(map[string]interface{}),
	}

	// 应用选项
	for k, v := range options {
		switch k {
		case "speed":
			if speed, ok := v.(float64); ok {
				segment.Speed = speed
			}
		case "volume":
			if volume, ok := v.(float64); ok {
				segment.Volume = volume
			}
		case "transform_x":
			if transformX, ok := v.(float64); ok {
				segment.TransformX = transformX
			}
		case "transform_y":
			if transformY, ok := v.(float64); ok {
				segment.TransformY = transformY
			}
		case "scale_x":
			if scaleX, ok := v.(float64); ok {
				segment.ScaleX = scaleX
			}
		case "scale_y":
			if scaleY, ok := v.(float64); ok {
				segment.ScaleY = scaleY
			}
		case "rotation":
			if rotation, ok := v.(float64); ok {
				segment.Rotation = rotation
			}
		default:
			segment.ExtraParams[k] = v
		}
	}

	t.Segments = append(t.Segments, segment)
	return &t.Segments[len(t.Segments)-1]
}

// AddAudioSegment 添加音频片段到轨道
func (t *Track) AddAudioSegment(materialID string, start, end, targetStart float64, options map[string]interface{}) *Segment {
	segment := Segment{
		ID:          uuid.New().String(),
		MaterialID:  materialID,
		Start:       start,
		End:         end,
		TargetStart: targetStart,
		Speed:       1.0,
		Volume:      1.0,
		Effects:     []Effect{},
		ExtraParams: make(map[string]interface{}),
	}

	// 应用选项
	for k, v := range options {
		switch k {
		case "speed":
			if speed, ok := v.(float64); ok {
				segment.Speed = speed
			}
		case "volume":
			if volume, ok := v.(float64); ok {
				segment.Volume = volume
			}
		default:
			segment.ExtraParams[k] = v
		}
	}

	t.Segments = append(t.Segments, segment)
	return &t.Segments[len(t.Segments)-1]
}

// AddTextSegment 添加文本片段到轨道
func (t *Track) AddTextSegment(text string, start, end float64, options map[string]interface{}) *Segment {
	segment := Segment{
		ID:          uuid.New().String(),
		MaterialID:  uuid.New().String(),
		Start:       start,
		End:         end,
		TargetStart: 0.0,
		Text:        text,
		FontName:    "SourceHanSansCN_Regular",
		FontSize:    30.0,
		FontColor:   "#FFFFFF",
		TransformX:  0.0,
		TransformY:  0.0,
		Effects:     []Effect{},
		ExtraParams: make(map[string]interface{}),
	}

	// 应用选项
	for k, v := range options {
		switch k {
		case "font_name":
			if fontName, ok := v.(string); ok {
				segment.FontName = fontName
			}
		case "font_size":
			if fontSize, ok := v.(float64); ok {
				segment.FontSize = fontSize
			}
		case "font_color":
			if fontColor, ok := v.(string); ok {
				segment.FontColor = fontColor
			}
		case "transform_x":
			if transformX, ok := v.(float64); ok {
				segment.TransformX = transformX
			}
		case "transform_y":
			if transformY, ok := v.(float64); ok {
				segment.TransformY = transformY
			}
		default:
			segment.ExtraParams[k] = v
		}
	}

	t.Segments = append(t.Segments, segment)
	return &t.Segments[len(t.Segments)-1]
}

// AddImageSegment 添加图片片段到轨道
func (t *Track) AddImageSegment(materialID string, start, end float64, options map[string]interface{}) *Segment {
	segment := Segment{
		ID:          uuid.New().String(),
		MaterialID:  materialID,
		Start:       start,
		End:         end,
		TargetStart: 0.0,
		TransformX:  0.0,
		TransformY:  0.0,
		ScaleX:      1.0,
		ScaleY:      1.0,
		Rotation:    0.0,
		Effects:     []Effect{},
		ExtraParams: make(map[string]interface{}),
	}

	// 应用选项
	for k, v := range options {
		switch k {
		case "transform_x":
			if transformX, ok := v.(float64); ok {
				segment.TransformX = transformX
			}
		case "transform_y":
			if transformY, ok := v.(float64); ok {
				segment.TransformY = transformY
			}
		case "scale_x":
			if scaleX, ok := v.(float64); ok {
				segment.ScaleX = scaleX
			}
		case "scale_y":
			if scaleY, ok := v.(float64); ok {
				segment.ScaleY = scaleY
			}
		case "rotation":
			if rotation, ok := v.(float64); ok {
				segment.Rotation = rotation
			}
		default:
			segment.ExtraParams[k] = v
		}
	}

	t.Segments = append(t.Segments, segment)
	return &t.Segments[len(t.Segments)-1]
}

// AddEffect 添加特效到片段
func (s *Segment) AddEffect(effectType string, params map[string]interface{}) *Effect {
	effect := Effect{
		ID:     uuid.New().String(),
		Type:   effectType,
		Params: params,
	}

	s.Effects = append(s.Effects, effect)
	return &s.Effects[len(s.Effects)-1]
}

// AddKeyframe 添加关键帧到片段
func (s *Segment) AddKeyframe(time float64, property string, value interface{}, parameters map[string]interface{}) *Keyframe {
	keyframe := Keyframe{
		Time:       time,
		Property:   property,
		Value:      value,
		Parameters: parameters,
	}

	s.Keyframes = append(s.Keyframes, keyframe)
	return &s.Keyframes[len(s.Keyframes)-1]
}

// generateDraftID 生成草稿ID
func generateDraftID() string {
	unixTime := time.Now().Unix()
	uniqueID := uuid.New().String()[0:8] // 取UUID的前8位
	return fmt.Sprintf("dfd_cat_%d_%s", unixTime, uniqueID)
}

// GenerateDraftURL 生成草稿URL
func GenerateDraftURL(draftDomain, previewRouter, draftID string) string {
	return util.GenerateDraftURL(draftDomain, previewRouter, draftID)
}
